import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';

import 'package:laos_mall/common/utils/widget_util.dart';
import 'package:laos_mall/common/widght/custom_tab_indicator.dart';
import 'package:laos_mall/common/widght/dropdown/custom_dropdown.dart';
import 'package:laos_mall/common/widght/textfiled_widget.dart';
import 'package:laos_mall/models/category/category_model.dart';
import 'package:laos_mall/pages/main/catergory/search_product/view.dart';
import 'package:laos_mall/pages/main/widgets/product_item.dart';

import '../../../common/widght/expansion_title_widget.dart';
import '../../../common/widght/flutter_popup/flutter_popup.dart';
import 'logic.dart';

class CatergoryPage extends StatelessWidget {
  CatergoryPage({Key? key}) : super(key: key);

  // final logic = Get.find<CatergoryLogic>();
  final logic = Get.put(CatergoryLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CatergoryLogic>(builder: (logic) {
      if (logic.model == null) {
        return _buildLoadingBuild();
      } else {
        return  Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            title: WidgetUtil.getSearchBar(
              type: TextFormFieldWidgetType.choose,
              showArrowIcon: false,
              onTap: () {
                Get.to(() => SearchProductPage());
              },
            ),
          ),
          body: Column(
            children: <Widget>[
              Row(
                children: [
                  // 一级分类 TabBar
                  TabBar(
                    isScrollable: true,
                    tabs: logic.model?.category_tree
                            ?.map((e) => Tab(text: e.category_name))
                            .toList() ??
                        [],
                    // indicatorPadding:
                    //     EdgeInsets.only(bottom: 5.h, left: 8, right: 8),
                    indicatorSize: TabBarIndicatorSize.label,
                    indicator: CustomTabIndicator(),
                    controller: logic.tabController,
                  )
                      .addContainer(height: 32.h, color: Colors.transparent)
                      .addExpand(),
                  expandCategory(false),
                ],
              ),
              PositionedDropdown(
                key: logic.dropDownKey,
                itemBuild: (context,index){
                  var e = logic.model?.category_tree?[index];
                  // 构建三级折叠效果
                  Widget thirdItem(Category_tree child,int level,{Category_tree? category1,Category_tree? category2,Category_tree? category3}){
                    return Row(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            color: AppColor.textColor,
                            borderRadius: BorderRadius.circular(1.5),
                          ),
                          width: 3,
                          height: 3,
                          margin: EdgeInsets.only(left: 10.w, right: 10.w),
                        ),
                        Text(child.category_name ?? ""),
                      ],
                    ).addPadding(EdgeInsets.symmetric(horizontal: 20.w),).addContainer(height: 25.h).addGestureTap(() {
                      logic.dropDownKey.currentState?.hideDropdown();
                      logic.jumpTabIndex(category1!,category2: category2,category3: category3);
                    });
                  }
                  Widget buildItem(Category_tree? e) {
                    if (e?.children == null || e!.children!.isEmpty) {
                        return thirdItem(e!,0,category1: e);
                    }
                    return ExpansionTileWidget(
                      initiallyExpanded: true,
                      expandedAlignment: Alignment.centerLeft,
                      expandedCrossAxisAlignment: CrossAxisAlignment.end,
                      title: e.category_name ?? "",
                      children: e.children?.map((child) {
                        if (child.children == null || child.children!.isEmpty) {
                          return thirdItem(child,1,category1: e,category2: child);
                        }
                        return ExpansionTileWidget(
                          initiallyExpanded: false,
                          expandedAlignment: Alignment.centerLeft,
                          expandedCrossAxisAlignment: CrossAxisAlignment.end,
                          title: child.category_name,
                          children: child.children?.map((grandChild) {
                            if (grandChild.children == null || grandChild.children!.isEmpty) {
                              return thirdItem(grandChild,2,category1: e,category2:child,category3: grandChild);
                            }
                            return Row(
                              children: [
                            Container(
                            decoration: BoxDecoration(
                            color: AppColor.textColor,
                              borderRadius: BorderRadius.circular(1.5),
                            ),
                              width: 3,
                              height: 3,
                              margin: EdgeInsets.only(left: 10.w, right: 10.w),
                            ),
                            Text(grandChild.category_name),
                            ],
                            ).addGestureTap(() {
                              logic.dropDownKey.currentState?.hideDropdown();
                            });
                          }).toList() ?? [],
                          child: Text(
                            child.category_name,
                            style: AppStyle.subtitleStyle,
                          ),
                          alignment: MainAxisAlignment.start,
                        ).addContainer(
                          color: Colors.transparent,
                          padding: EdgeInsets.symmetric(horizontal: 30.w),
                        );
                      }).toList() ?? [],
                      childHeight: 32.h,
                      child: Text(
                        e?.category_name ?? "",
                        style: AppStyle.subtitleStyle,
                      ),
                      alignment: MainAxisAlignment.start,
                    ).addContainer(
                      // color: Colors.green,
                      // margin: EdgeInsets.only(bottom: 3),
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                    );
                  }
                  return buildItem(e);
                },
                items: logic.model?.category_tree ?? [],
                type: PositionedDropdownType.category,
                onItemSelected: (selectedItem) {
                  print('Selected: $selectedItem');
                },
                width: ScreenUtil().screenWidth, // 自定义宽度
              ),
              Expanded(
                child: ExtendedTabBarView(
                  shouldIgnorePointerWhenScrolling: false,
                  controller: logic.tabController,
                  children: _buildCategoryTabs(logic.model?.category_tree),
                ),
              ),
            ],
          ),
        );
      }
    });
  }

  /// 构建分类 TabBar 和 ExtendedTabBarView
  List<Widget> _buildCategoryTabs(List<Category_tree>? categoryTree) {
    if (categoryTree == null || categoryTree.isEmpty) {
      return []; // 返回空列表
    }

    return categoryTree.map((category1) {
      if (category1.children == null) {
        return ProductItemWidget(name: category1.category_id.toString());
      } else {
        TabController tabController1 = TabController(
            length: category1.children?.length ?? 0, vsync: logic,initialIndex: logic.selIndex1 > (category1.children?.length  ?? 0)? 0 :logic.selIndex1);
        logic.tabController1 = tabController1;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 二级分类 TabBar
            TabBar(
              isScrollable: true,
              indicatorColor: Colors.transparent,
              tabs: category1.children
                      ?.map((e) => Tab(text: e.category_name))
                      .toList() ??
                  [],
              controller: tabController1,
            ).addContainer(height: 32.h, color: Colors.transparent),
            // Expanded(child: TabBarView(children: _buildSubCategoryTabs(category1.children),controller: logic.tabController1,))
            Expanded(
              child: ExtendedTabBarView(
                shouldIgnorePointerWhenScrolling: false,
                controller: logic.tabController1,
                children: _buildSubCategoryTabs(category1.children),
              ),
            )
          ],
        );
      }
    }).toList();
  }

  /// 构建子分类 TabBar 和 ExtendedTabBarView
  List<Widget> _buildSubCategoryTabs(List<Category_tree>? subCategories) {
    print("二级分类${subCategories?.length}");
    if (subCategories == null || subCategories.isEmpty) {
      return []; // 返回空列表
    }

    return subCategories.map((category2) {
      if (category2.children == null) {
        return ProductItemWidget(name: category2.category_id.toString());
      } else {
        TabController tabController2 = TabController(
            length: category2.children?.length ?? 0, vsync: logic);
        logic.tabController2 = tabController2;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 三级分类 TabBar
            TabBar(
              isScrollable: true,
              indicatorColor: Colors.transparent,
              tabs: category2.children
                      ?.map((e) => Tab(text: e.category_name))
                      .toList() ??
                  [],
              controller: logic.tabController2,
            ),
            Expanded(
              child: ExtendedTabBarView(
                shouldIgnorePointerWhenScrolling: false,
                controller: logic.tabController2,
                // link: true,
                // cacheExtent: 1,
                children: _buildProductWidgets(category2.children),
              ),
            ),
          ],
        );
      }
    }).toList();
  }

  /// 构建产品列表
  List<Widget> _buildProductWidgets(List<Category_tree>? subCategories) {
    if (subCategories == null || subCategories.isEmpty) {
      return []; // 返回空列表
    }

    return subCategories.map((category3) {
      return ProductItemWidget(name: category3.category_id.toString());
    }).toList();
  }

  _buildLoadingBuild() {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Container(
          width: double.infinity,
          height: 32.h,
          color: AppColor.primaryColor,
        ).addSkeleton(),
        // toolbarHeight: 80.h,
      ),
      body: Column(
        children: <Widget>[
          Row(
            children: [
              TabBar(
                isScrollable: true,
                tabs: [
                  // Tab(text: "Woman",child: Text("Woman",textAlign: TextAlign.center,style: AppStyle.textStyle,).addContainer(width: 55,color: Colors.transparent),),
                  Tab(text: "Woman").addContainer(width: 60).addSkeleton(),
                  Tab(text: "man").addContainer(width: 60).addSkeleton()
                ],
                indicatorPadding:
                    EdgeInsets.only(bottom: 5.h, left: 8, right: 8),
                indicatorSize: TabBarIndicatorSize.label,
                controller: logic.tabController,
              )
                  .addContainer(height: 20.h, color: Colors.transparent)
                  .addExpand(),
              expandCategory(true),
            ],
          ),
          Expanded(
            child: ExtendedTabBarView(
              shouldIgnorePointerWhenScrolling: false,
              controller: logic.tabController,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    TabBar(
                      isScrollable: true,
                      indicatorColor: Colors.transparent,
                      tabs: [
                        Tab(text: 'Tab00')
                            .addContainer(width: 60)
                            .addSkeleton(),
                        Tab(text: 'Tab01')
                            .addContainer(width: 60)
                            .addSkeleton(),
                        Tab(text: 'Tab02')
                            .addContainer(width: 60)
                            .addSkeleton(),
                      ],
                      controller: logic.tabController1,
                    ).addContainer(height: 20.h, color: Colors.transparent),
                    Expanded(
                      child: ExtendedTabBarView(
                        shouldIgnorePointerWhenScrolling: false,
                        controller: logic.tabController1,
                        children: <Widget>[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              TabBar(
                                isScrollable: true,
                                indicatorColor: Colors.transparent,
                                tabs: List.generate(4, (index) {
                                  bool isSel =
                                      logic.tabController2.index == index;
                                  return Tab(
                                    child: Text(
                                      "Tab000",
                                      style: AppStyle.textSmallStyle.copyWith(
                                          color: !isSel
                                              ? AppColor.textColor
                                              : Colors.white),
                                    ),
                                  )
                                      .addContainer(
                                          color: AppColor.primaryColor,
                                          height: 20.h,
                                          width: 60,
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 5.w),
                                          border: isSel
                                              ? null
                                              : AppStyle.defaultBorder())
                                      .addSkeleton();
                                }),
                                controller: logic.tabController2,
                                onTap: (index) {
                                  logic.update();
                                },
                              ),
                              Expanded(
                                child: ExtendedTabBarView(
                                  shouldIgnorePointerWhenScrolling: false,
                                  controller: logic.tabController2,
                                  // if link is true and current TabBarView over scroll,
                                  // it will check and scroll ancestor or child TabBarView.
                                  link: true,
                                  // cache page count
                                  // default is 0.
                                  // if cacheExtent is 1, it has two pages in cache
                                  cacheExtent: 1,
                                  children: <Widget>[
                                    ProductItemWidget(name: 'Tab000'),
                                    ListWidget('Tab001'),
                                    ListWidget('Tab002'),
                                    ListWidget('Tab003'),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          const ListWidget('Tab01'),
                          const ListWidget('Tab02'),
                        ],
                      ),
                    ),
                  ],
                ),
                const ListWidget('Tab1'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  expandCategory(bool isLoad) {
    if (isLoad) {
      return Container(
        width: 20.h,
        height: 20.h,
        color: Colors.white,
        margin: EdgeInsets.only(right: 16),
      ).addSkeleton();
    } else {
      return Container(
        key: logic.btnKey,
        margin: EdgeInsets.only(right: 15.h),
        width: 32.h,
        height: 32.h,
        alignment: Alignment.centerRight,
        padding: EdgeInsets.zero,
        child: Icon(Icons.keyboard_arrow_down),
      ).addGestureTap(() {
        logic.dropDownKey.currentState?.showDropdown(logic.btnKey.getMaxY);
      });
      return PositionedDropdown(
        key: logic.btnKey,
        items: ["item1", "item2"],
        type: PositionedDropdownType.search,
        onItemSelected: (selectedItem) {
          print('Selected: $selectedItem');
        },
        width: ScreenUtil().screenWidth, // 自定义宽度
      );

      // return CustomPopup(
      //   showArrow: false,
      //   // contentPadding: EdgeInsets.zero,
      //   content: _buildExpansionItem(),
      //   child: Container(
      //     margin: EdgeInsets.only(right: 15.h),
      //     width: 32.h,
      //     height: 32.h,
      //     alignment: Alignment.centerRight,
      //     padding: EdgeInsets.zero,
      //     child: Icon(Icons.keyboard_arrow_down),
      //   ),
      // );
    }
  }

}

class ListWidget extends StatelessWidget {
  const ListWidget(
    this.tabKey, {
    Key? key,
    this.scrollDirection = Axis.vertical,
  }) : super(key: key);

  final String tabKey;
  final Axis scrollDirection;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext c, int i) {
        return Container(
          //decoration: BoxDecoration(border: Border.all(color: Colors.orange,width: 1.0)),
          alignment: Alignment.center,
          height: 60.0,
          child: Text('$tabKey : List$i'),
        );
      },
      itemCount: 100,
      scrollDirection: scrollDirection,
    );
  }
}
